package com.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.Employee;
import com.pojo.Privilege;

import com.service.employeeservice.EmployeeService;


/**
* @author chengfei
* @date 2018年8月14日
*/
public class InterceptorUser implements HandlerInterceptor{

	@Resource  
    private  EmployeeService employeeService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String url= request.getRequestURI();
		Object username = request.getSession().getAttribute("loginEmployee");
		//如果 访问的 是 登陆页面  允许 直接 访问
		if(url.contains("logincf") || url.contains("loginIncf")){
			String loginCookieEmployeeUserName = "";
			String loginCookieEmployeePassword = "";
			Cookie[] cookies = request.getCookies();
			if(null!=cookies){  
		    	for(Cookie cookie : cookies){  
			    		if("loginEmployeeusername".equals(cookie.getName())){
			    			loginCookieEmployeeUserName = cookie.getValue();
			    		}else if("loginEmployeePassword".equals(cookie.getName())){
			    			loginCookieEmployeePassword = cookie.getValue();
			    		}
		    	}  
		    	if(!"".equals(loginCookieEmployeeUserName) && !"".equals(loginCookieEmployeePassword)){
		    		Employee e = new Employee();
		    		e.setEmployeeusername(loginCookieEmployeeUserName);   
		    		e.setEmployeepassword(loginCookieEmployeePassword);   
		    		Employee employee=employeeService.login(e);     
		    		if(loginCookieEmployeePassword.equals(employee.getEmployeepassword())){
		    			List<Privilege> privileges = employeeService.getPrivilege(employee.getEmployeeid());
		    			request.getSession().setAttribute("privileges", privileges);
		    			request.getSession().setAttribute("loginUser", employee);
		    		}
		    	request.getRequestDispatcher("indexcf2.html").forward(request, response);	
		    	}
		    	
			} 
			return true;
		}
		//从session中 获取  是否有 用户登陆
		if(username!=null){
			return true;
		}
		//如果 没有登录 且 访问的 地址不是   登陆页面则
		request.getRequestDispatcher("logincf.html").forward(request, response);
		return false;

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView arg3)
			throws Exception {
	}
	
}
